package org.darkforest.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.darkforest.vo.ExpressDetailVo;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by abao on 2015/12/25.
 */
public class ExpressDetailUtil {
    public static final String KEY = "637bccf9d09563da";
    public static final String SHOWJSON = "0";
    public static final String SHOWXML = "1";
    public static final String SHOWHTML = "2";
    public static final String SHOWTEXT = "3";

    public static final String BACKMUCH = "1";
    public static final String BACKONE = "0";

    public static final String ORDERDESC = "desc";
    public static final String ORDERASC = "asc";

    private ExpressDetailUtil(){

    }

    /**
     * id	String	是	身份授权key，请 快递查询接口 进行申请（大小写敏感）
     * com	String	是	要查询的快递公司代码，不支持中文
     * nu	String	是	要查询的快递单号，请勿带特殊符号，不支持中文（大小写不敏感）
     * valicode	String	是	已弃用字段，无意义，请忽略。
     * show	String	是	返回类型： 0：返回json字符串，1：返回xml对象，2：返回html对象，3：返回text文本。 如果不填，默认返回json字符串。
     * muti	String	是	返回信息数量：1:返回多行完整的信息，0:只返回一行信息。不填默认返回多行。
     * order	String	是	排序： desc：按时间由新到旧排列， asc：按时间由旧到新排列。不填默认返回倒序（大小写不敏感）
     */
    public static String  expressDetailFromKuaiDi100(String com,String nu,String show,String muti, String order){
        String content ="";
        try
        {
            URL url= new URL("http://api.kuaidi100.com/api?id="+KEY+"&com="+com+"&nu="+nu+"&show="+show+"&muti="+muti+"&order="+order);
            URLConnection con=url.openConnection();
            con.setAllowUserInteraction(false);
            InputStream urlStream = url.openStream();
            String type = con.guessContentTypeFromStream(urlStream);
            String charSet=null;
            if (type == null)
                type = con.getContentType();

            if (type == null || type.trim().length() == 0 || type.trim().indexOf("text/html") < 0)
                return "";

            if(type.indexOf("charset=") > 0)
                charSet = type.substring(type.indexOf("charset=") + 8);

            byte b[] = new byte[10000];
            int numRead = urlStream.read(b);
            content = new String(b, 0, numRead);
            while (numRead != -1) {
                numRead = urlStream.read(b);
                if (numRead != -1) {
                    //String newContent = new String(b, 0, numRead);
                    String newContent = new String(b, 0, numRead, charSet);
                    content += newContent;
                }
            }
            //System.out.println("content:" + content);
            urlStream.close();
        } catch (MalformedURLException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }finally {
            return  content;
        }

    }
    public static ExpressDetailVo expressDetail(){
        String jsonstr="{\"message\":\"ok\",\"status\":\"1\",\"state\":\"3\",\"data\":\n" +
                "            [{\"time\":\"2012-07-07 13:35:14\",\"context\":\"客户已签收\"},\n" +
                "             {\"time\":\"2012-07-07 09:10:10\",\"context\":\"离开 [北京石景山营业厅] 派送中，递送员[温]，电话[]\"},\n" +
                "             {\"time\":\"2012-07-06 19:46:38\",\"context\":\"到达 [北京石景山营业厅]\"},\n" +
                "             {\"time\":\"2012-07-06 15:22:32\",\"context\":\"离开 [北京石景山营业厅] 派送中，递送员[温]，电话[]\"},\n" +
                "             {\"time\":\"2012-07-06 15:05:00\",\"context\":\"到达 [北京石景山营业厅]\"},\n" +
                "             {\"time\":\"2012-07-06 13:37:52\",\"context\":\"离开 [北京_同城中转站] 发往 [北京石景山营业厅]\"},\n" +
                "             {\"time\":\"2012-07-06 12:54:41\",\"context\":\"到达 [北京_同城中转站]\"},\n" +
                "             {\"time\":\"2012-07-06 11:11:03\",\"context\":\"离开 [北京运转中心驻站班组] 发往 [北京_同城中转站]\"},\n" +
                "             {\"time\":\"2012-07-06 10:43:21\",\"context\":\"到达 [北京运转中心驻站班组]\"},\n" +
                "             {\"time\":\"2012-07-05 21:18:53\",\"context\":\"离开 [福建_厦门支公司] 发往 [北京运转中心_航空]\"},\n" +
                "             {\"time\":\"2012-07-05 20:07:27\",\"context\":\"已取件，到达 [福建_厦门支公司]\"}\n" +
                "            ]} ";
        JSONObject json = JSON.parseObject(jsonstr);
        ExpressDetailVo ev = JSON.toJavaObject(json, ExpressDetailVo.class);
        return ev;

    }



    /**
     * 快递查询接口方法
     *
     * @param key
     *            ：商家用户key值，在http://www.kuaidi100.com/openapi申请的
     * @param com
     *            ：快递公司代码，在http://www.kuaidi100.com/openapi网上的技术文档里可以查询到
     * @param nu
     *            ：快递单号，请勿带特殊符号，不支持中文（大小写不敏感）
     * @return 快递100返回的url，然后放入页面iframe标签的src即可
     * @see
     */
    public static  String searchkuaiDiInfo(String com, String nu)
    {
        String content = "";
        try
        {
            URL url = new URL("http://www.kuaidi100.com/applyurl?key=" + KEY + "&com=" + com
                    + "&nu=" + nu);
            URLConnection con = url.openConnection();
            con.setAllowUserInteraction(false);
            InputStream urlStream = url.openStream();
            byte b[] = new byte[10000];
            int numRead = urlStream.read(b);
            content = new String(b, 0, numRead);
            while (numRead != -1)
            {
                numRead = urlStream.read(b);
                if (numRead != -1)
                {
                    // String newContent = new String(b, 0, numRead);
                    String newContent = new String(b, 0, numRead, "UTF-8");
                    content += newContent;
                }
            }
            urlStream.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return content;
    }

    public static void main(String args[]){
//        String context = ExpressDetailUtil.expressDetailFromKuaiDi100("yuantong","880705913770294388","0","1","desc");
       // String context = ExpressDetailUtil.searchkuaiDiInfo("yuantong","880705913770294388");
        String context = ExpressDetailUtil.searchkuaiDiInfo("yunda","3101794008329");
        System.out.println(context);
    }

}
